#!/usr/bin/env python
# -*- coding: utf-8 -*-

from base64 import b64encode, b64decode

import md5
import os, os.path, time
import tempfile

from potherb import log
from potherb.cellstore import CellStore


def test1(storefile) :
    min_key = 1
    max_key = 65536 + 1

    time_start = time.time()
    store = CellStore(storefile)
    for k in range(min_key, max_key) :
        data = '%16d' % k
        key = md5.new(data).hexdigest()
        store.append(key, data)
    del store
    time_stop = time.time()
    time_last = time_stop - time_start
    count_records = max_key - min_key
    tps = count_records / time_last
    filesize = os.path.getsize(storefile)
    log.info('WRITE records:%d time-last:%.2f seconds tps:%.2f file-size:%d bytes', count_records, time_last, tps, filesize)

    time_start = time.time()
    store = CellStore(storefile)
    for k in range(min_key, max_key) :
        data = '%16d' % k
        key = md5.new(data).hexdigest()

        k,v = store.next()
        if not (k == key and v == data) :
            log.error('MISMATCH %s vs %s', key, k)
    del store
    time_stop = time.time()
    time_last = time_stop - time_start
    count_records = max_key - min_key
    tps = count_records / time_last
    filesize = os.path.getsize(storefile)
    log.info(' READ records:%d time-last:%.2f seconds tps:%.2f file-size:%d bytes', count_records, time_last, tps, filesize)
    # test1()


if __name__=='__main__' :
    log.enableDebug()

    tempfd, tempname = tempfile.mkstemp(suffix='.store', prefix='pot')
    log.debug('temporary file : %s', tempname)
    try :
        try :
            test1(tempname)
        except :
            raise
    finally :
        os.close(tempfd)
        os.remove(tempname)

